package de.koller.planet2D;

import de.koller.aframe.util.thread.ICommand;
import de.koller.aframe.util.thread.ILoopHandler;
import de.koller.aframe.util.thread.ThreadRootHandle;
import de.koller.oceanFramework.tree.Child;
import de.koller.planet2D.container.RenderContainer;
import de.koller.planet2D.frame.PreviewFrame;

public class PRoot extends PNode implements ICommand, ILoopHandler {
	
	public final ThreadRootHandle thread = new ThreadRootHandle( "calcthread" );
	@Child public final PreviewFrame previewFrame = new PreviewFrame();
	@Child public final RenderContainer renderContainer = new RenderContainer();
	private boolean update = false;
	
	@Override
	protected void init() {
		proot = this;
		super.init();
		proot = this;
	}
	
	@Override
	protected void postChildInit() {
		super.postChildInit();
		
		thread.setLoopHandler( this );
		thread.start();
	}

	public void call( ICommand command ) {
		thread.call( command );
	}
	
	public void updateThis() {
		if( update )
			return;
		update = true;
		thread.call( this );
	}

	@Override
	public void handle( Object... params ) {
		this.updating( 1 );
		this.rendering( 1 );
		update = false;
	}
	
	public void exit() {
		this.call( new Release() );
	}

	@Override
	public void loopHandle() {
		ICommand cmd = this.thread.pop();
		cmd.handle();
	}
	
	private class Release implements ICommand {

		@Override
		public void handle( Object... params ) {
			releasing();
			thread.stop();
		}
		
	}

}
